package org.ourguy.mymoviesandshows.utils;

import org.ourguy.mymoviesandshows.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;

/**
 * AsyncTask which loads image from the cache and bind it to a image view.
 * @author lubenivanov
 */

public class LoadImageViewAsync extends AsyncTask<Void, Void, Integer> {
    private static final int SUCCESS = 0;

    private static final int ERROR = 1;

    private String imagePath;

    private ImageView imageView;

    private Context context;
    
    private Boolean thumbnail;

    /**
     * @param path The url of the image.
     * @param imageView Image view to which the image will be attached.
     * @param context Context of the imageView.
     * @param thumbnail true if you want attached image to be small thumbnail, false otherwise.
     */
    public LoadImageViewAsync(String path, ImageView imageView, Context context, Boolean thumbnail) {
        imagePath = path;
        this.imageView = imageView;
        this.context = context;
        this.thumbnail = thumbnail;
    }
    
    /**
     * @param imageView Image view to which the image will be attached.
     * @param context Context of the imageView.
     * @param thumbnail true if you want attached image to be small thumbnail, false otherwise.
     */
    public LoadImageViewAsync(String path, ImageView imageView, Context context) {
        imagePath = path;
        this.imageView = imageView;
        this.context = context;
        this.thumbnail = false;
    }

    @Override
    protected void onPreExecute() {
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setImageResource(R.drawable.ic_action_refresh);
    }

    @Override
    protected Integer doInBackground(Void... params) {
        int resultCode;

        if (isCancelled()) {
            return null;
        }
        
        if (ImageCache.getInstance(context).getIfNotBusy(imagePath, false) != null) {
            resultCode = SUCCESS;
        } else {
            resultCode = ERROR;
        }

        return resultCode;
    }

    @Override
    protected void onPostExecute(Integer resultCode) {
        switch (resultCode) {
            case SUCCESS:
                Bitmap bitmap = thumbnail? ImageCache.getInstance(context).getThumb(imagePath,false):
                	ImageCache.getInstance(context).get(imagePath);
                if (bitmap != null) {
                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                    imageView.setImageBitmap(bitmap);
                    return;
                }
                // no break because image could be null (got deleted, ...)
            default:
                // fallback
                imageView.setImageResource(R.drawable.ic_launcher);
                break;
        }
    }
}
